package com.feel.easycloud.controller;

import cn.hutool.core.codec.Base64;
import com.feel.easycloud.enums.ApiResultEnum;
import com.feel.easycloud.utils.ApiResult;
import com.feel.easycloud.utils.CodeUtils;
import com.feel.easycloud.utils.SnowFlake;
import com.feel.easycloud.vo.graphic.VerificationCodeResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class GraphicController {

    private static Logger logger = LoggerFactory.getLogger(GraphicController.class);

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @PostMapping("/graphic/generate/verificationcode")
    public ApiResult<VerificationCodeResponseVo> createSystemUser(){
        CodeUtils codeUtils = new CodeUtils();
        BufferedImage verificationcodeImange = codeUtils.generateCaptcha();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            logger.info(codeUtils.getText());
            ImageIO.write(verificationcodeImange, "JPEG", stream);
            BASE64Encoder encoder = new BASE64Encoder();
            String jpg_base64 = encoder.encodeBuffer(stream.toByteArray()).trim();//转换成base64串
            jpg_base64 = jpg_base64.replaceAll("\n", "")
                    .replaceAll("\r", "");//删除 \r\n
            String uuid = SnowFlake.getInstance().uuid();
            VerificationCodeResponseVo responseVo = new VerificationCodeResponseVo();
            responseVo.setJpgBase64("data:image/jpg;base64," + jpg_base64);
            responseVo.setVerificationKey(uuid);
            redisTemplate.opsForValue().set(uuid,codeUtils.getText());
            redisTemplate.expire(uuid,60L, TimeUnit.SECONDS);
            return ApiResult.success(responseVo);
        } catch (IOException e) {
            logger.error(e.getMessage());
            return ApiResult.fail(ApiResultEnum.CODE_100002);
        }
    }

}
